<?php

namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Log;
use think\Response;
use Throwable;

/**
 * 兼容版本的应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 记录异常详细信息
        $context = [
            'exception_class' => get_class($exception),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'request_url' => request()->url(true),
            'request_method' => request()->method(),
            'ip' => request()->ip(),
        ];

        logs('系统异常: ' . $exception->getMessage(), $context,'error');

        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {

        $traceId = uniqid('trace_', true);

        // 验证异常
        if ($e instanceof ValidateException) {
            return json([
                'code' => 2002,
                'message' => $e->getError(),
                'result' => [],
                'trace_id' => $traceId,
                'timestamp' => time(),
            ])->code(400);
        }

        // HTTP异常
        if ($e instanceof HttpException) {
            return json([
                'code' => $e->getStatusCode(),
                'message' => $e->getMessage() ?: '请求错误',
                'result' => [],
                'trace_id' => $traceId,
                'timestamp' => time(),
            ])->code($e->getStatusCode());
        }

        // 数据库异常
        if ($e instanceof ModelNotFoundException || $e instanceof DataNotFoundException) {
            return json([
                'code' => 4000,
                'message' => '请求的资源不存在',
                'result' => [],
                'trace_id' => $traceId,
                'timestamp' => time(),
            ])->code(404);
        }

        // 系统异常
        $message = app()->isDebug() ? $e->getMessage() : '系统错误';
        return json([
            'code' => 1000,
            'message' => $message,
            'result' => app()->isDebug() ? [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => explode("\n", $e->getTraceAsString()),
            ] : [],
            'trace_id' => $traceId,
            'timestamp' => time(),
        ])->code(500);
    }
}
